# This file runs a Python program, making sure that stdout and stderr are
# flushed after every write.
# It also sends secret signals to indicate when the console should read
# a line.
import sys, os

# Makes sure that the stream is flushed after every write.
class FakeOutput:
	def __init__(self, stream, is_error = False):
		self.stream   = stream
		self.is_error = is_error

	def write(self, text):
		text_len = len(text)
		# Handle Windows console newlines
		if len(os.linesep) == 2:
			text_len += text.count('\n')
		self.stream.write('E' if self.is_error else 'O')
		self.stream.write('%06d' % text_len)
		self.stream.write(text)
		self.stream.flush()

# When input is requested, this writes #IN to stdout.
# That signal is intercepted to put the console into writing mode.
class FakeInput:
	def __init__(self, stream):
		self.stream = stream

	def readline(self):
		sys.__stdout__.write('##INPUT')
		sys.__stdout__.flush()
		data = self.stream.readline()
		if os.linesep != '\n':
			data = data.replace(os.linesep, '\n')
		return data

# See if the program is available at the command line.
file_to_run = None
if len(sys.argv) > 1:
	file_to_run = sys.argv[1]
	del sys.argv[1] # so that the file we're running doesn't see this argument.
else:
	# Read the program from stdin if desired.
	program_length = int(sys.stdin.readline())
	program = sys.stdin.read(program_length)

# Change all the streams
# TODO: use locking to avoid contention for stdout.
stdout = sys.stdout
sys.stdout = FakeOutput(stdout)
sys.stderr = FakeOutput(stdout, is_error = True)
sys.stdin  = FakeInput(sys.stdin)

# Now, execute it.
# TODO: trap errors.
if file_to_run:
	execfile(file_to_run)
else:
	exec program

# Now, let parent know we're done.
sys.__stdout__.write('###DONE')
sys.__stdout__.flush()
sys.__stdin__.readline()
